#include "head.hpp"

void GetMessage(int fd)
{
    char buffer[128];
    while (true)
    {
        memset(buffer, 0, sizeof buffer);
        ssize_t s = read(fd, buffer, (sizeof buffer) - 1);
        if (s > 0)
        {
            cout << "get a message: " << buffer << endl;
        }
        else if (s == 0)
        {
            cout << "client quit, me too! " << endl;
            break;
        }
        else
        {
            perror("读取失败");
            exit(2);
        }
    }
}

int main()
{
    // 1.创建公共的key值
    key_t key = ftok(PATH_SHM, ID); // 通过共享内存的路径和ID随机值创建key
    assert(key != -1);
    cout << "创建key值成功, key: " << key << endl;

    // 2.创建共享内存
    int shmid = shmget(key, SHM_SIZE, IPC_CREAT | IPC_EXCL | 0666);
    assert(shmid != -1);
    cout << "创建共享内存成功, shmid: " << shmid << endl;

    // 3.关联共享内存
    char *shmaddr = (char *)shmat(shmid, nullptr, 0);
    assert(shmaddr != nullptr);
    cout << "关联共享内存成功, shmaddr: " << shmaddr << endl;
    //sleep(10);

    // 4.这里为通信逻辑....

    // 5.去关联
    int n = shmdt(shmaddr);
    assert(n != -1);
    cout << "去关联成功, n: " << n << endl;

    // 6.删除共享内存
    int n1 = shmctl(shmid, IPC_RMID, nullptr);
    assert(n1 != -1);
    cout << "删除共享内存成功, n1: " << n1 << endl;
    return 0;
}